package com.nf.health.app.inquiry.docdetail;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.mydoctor.activity.MyNewDoctorActivity;
import com.nf.health.app.customview.CircleImageView;
import com.nf.health.app.glide.GlideUtil;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.Apis;
import com.nf.health.app.inquiry.InquiryHintDialog;
import com.nf.health.app.inquiry.bean.PayParamsModel;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.BigDecimalUtils;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.MathUtils;
import com.nf.health.app.utils.ModelUtils;
import com.nf.health.app.utils.pay.PayResult;


import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 去购买服务接口
 *
 * @于亚豪
 */
public class PayOrderServiceActivity extends BaseActivity {
    private final String TOTTLE_ON = "com.nf.totlebutton.on";
    private final String TOTTLE_OFF = "com.nf.totlebutton.off";
    @Bind(R.id.iv_pay_service_header)
    CircleImageView iv_pay_service_header;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebar_title_tv;

    @Bind(R.id.tv_pay_service_header_name)
    TextView tv_pay_service_header_name;
    @Bind(R.id.tv_pay_service_header_type)
    TextView tv_pay_service_header_type;
    @Bind(R.id.tv_pay_service_time)
    TextView tv_pay_service_time;
    @Bind(R.id.tv_pay_service_price)
    TextView tv_pay_service_price;//医生服务费
    @Bind(R.id.tv_pay_service_currency)
    TextView tv_pay_service_currency;//健康币的数量
    @Bind(R.id.tb_pay_service)
    ToggleButton tb_pay_service;//是不是开启服务
    @Bind(R.id.ed_health_currency_num)
    EditText ed_health_currency_num;//使用多少个健康币
    @Bind(R.id.tv_pay_health_currrent)
    TextView tv_pay_health_currrent;//健康币换算的钱数
    @Bind(R.id.ll_payforservice)
    LinearLayout ll_payforservice;//

    @Bind(R.id.tv_pay_service_currency_tip)
    TextView tv_pay_service_currency_tip;//赠送健康币的提示
    @Bind(R.id.tb_pay_service_totle)
    TextView tb_pay_service_totle;//最后计算的总金额
    @Bind(R.id.btn_order_service_pay)
    TextView btn_order_service_pay;//去支付
    private double servicePrice = 0f;//服务的价格
    private double currentAllMoney  = 0;//计算得到总共的价格
    private double healthyCoinNum = 0;
    private   String money;
    /*支付宝支付结果码*/
    private static final String PAY_OK = "9000";// 支付成功
    private static final  String PAY_WAIT_CONFIRM = "8000";// 交易待确认
    private static final String PAY_NET_ERR = "6002";// 网络出错
    private static final String PAY_CANCLE = "6001";// 交易取消
    private static final String PAY_FAILED = "4000";// 交易失败/*内部类，处理支付宝支付结果*/
    private static final int SDK_PAY_FLAG = 1;
    private String doctorid = null,   buytype = null,  type = null ;
    double currentCoinNum = 0;
    private double  price = 0;
    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SDK_PAY_FLAG:
                    PayResult payResult = null;
                    try{
                        payResult = new PayResult((Map<String, String>) msg.obj);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, PAY_OK)) {//----------------------------------->支付成功
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        GetToast.useString(PayOrderServiceActivity.this, "购买服务成功");
                        InquiryHintDialog dialog = new InquiryHintDialog(PayOrderServiceActivity.this)
                                .setMyCancelable(false)
                                .setMyOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ActivityUtils.showActivity(PayOrderServiceActivity.this, MyNewDoctorActivity.class);
                                        finish();
                                    }
                                });
                        dialog.setWebContent(Apis.getTipUrl(Constants.H5_TIP_BUY_DOCTOR_SERVICE));
                        dialog.setCircleDialogAtter(0.8, 0.5);
                        dialog.setButtonSize(18);
                        if(!dialog.isShowing()){
                            dialog.show();
                        }
                        currentCoinNum = 0;
                    } else if (TextUtils.equals(resultStatus, PAY_FAILED)) {//------------------------->支付失败
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        GetToast.useString(PayOrderServiceActivity.this, ""+payResult.getMemo());
                    } else if (TextUtils.equals(resultStatus, PAY_CANCLE)) {//-------------------------->交易取消
                        GetToast.useString(PayOrderServiceActivity.this, ""+payResult.getMemo());
                    } else if (TextUtils.equals(resultStatus, PAY_NET_ERR)) {//------------------------->网络出现错误
                        GetToast.useString(PayOrderServiceActivity.this, ""+payResult.getMemo());
                    } else if (TextUtils.equals(resultStatus, PAY_WAIT_CONFIRM)) {//--------------------->交替等待
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_payorderservice);
        ButterKnife.bind(this);
        initView();
        initListener();
        loadHealthyCurreny();
        addEdittextListener();
    }

    private void loadHealthyCurreny() {
       // provider.getDoctorScore();
        //请求将健康的个数
        provider.getUserHealthMoenyNUm();
    }
    /**
     * 支付宝支付
     * 购买服务等接口
     *  @property (nonatomic,assign)buyType buytype ;// 1单次，2天/次，3周，4月，5季度，6半年，7一年
    //        @property (nonatomic,assign)payType paytype ;//1 家庭服务 2 付费咨询 3健康管理
     */
    private void payAliyunment() {
        if(tb_pay_service.isChecked()){//打开
            int  newPrice = (int) (currentAllMoney * 100);
            provider.createServiceOrder(doctorid, String.valueOf(newPrice),buytype, type, MathUtils.getFloats(currentCoinNum * 100) );
        }else{//关闭过
            int  newPrice = (int) (price * 100);
            provider.createServiceOrder(doctorid, String.valueOf(newPrice),buytype, type,  String.valueOf(0));
        }
    }

    private void initListener() {
        btn_order_service_pay.setOnClickListener(this);
    }

    private void initView() {
        titlebar_title_tv.setText("确认购买");
        String source1 = "<font color='#fc6f00'>赠送80个健康币</font>（健康币赠送以实付款金额发放）";
        tv_pay_service_currency_tip.setText(Html.fromHtml(source1));
        PayParamsModel payParamsModel = (PayParamsModel) getIntent().getSerializableExtra(Constants.DOCTOR_NEED_PARAMS);
        if(payParamsModel == null){
            return ;
        }
        GlideUtil.loadNetImg2(PayOrderServiceActivity.this, iv_pay_service_header, payParamsModel.getHeadImg(), R.drawable.default_head);
        tv_pay_service_header_name.setText(TextUtils.isEmpty(payParamsModel.getDoctorName()) ? "未知医生" : payParamsModel.getDoctorName());
        tv_pay_service_header_type.setText(TextUtils.isEmpty(payParamsModel.getServiceTrpe()) ? "" : payParamsModel.getServiceTrpe());
        price =Double.parseDouble(TextUtils.isEmpty(payParamsModel.getServiceMoney()) ? "0" : payParamsModel.getServiceMoney());
        tv_pay_service_price.setText( MathUtils.getFloats(price)+"元");
        String time  = "时间 1"+ (TextUtils.isEmpty(payParamsModel.getServicTime())? "0": payParamsModel.getServicTime());
        tv_pay_service_time.setText(time);
        buytype = ModelUtils.getBuyType(payParamsModel.getServicTime());
        doctorid = payParamsModel.getDoctorId();
        type = ModelUtils.getPayType(payParamsModel.getServiceTrpe());
        if(TextUtils.isEmpty(payParamsModel.getServiceMoney())){
            servicePrice = 0 ;
        }else if(payParamsModel.getServiceMoney().endsWith("元")){
            servicePrice = Double.parseDouble(payParamsModel.getServiceMoney().replace("", "元"));
        }else{
            servicePrice = Double.parseDouble(payParamsModel.getServiceMoney());
        }
        servicePrice = Double.parseDouble((TextUtils.isEmpty(payParamsModel.getServiceMoney()) ? "0" : payParamsModel.getServiceMoney()));

        money = "¥ "+ "<font color='#fc6f00'>"+servicePrice+"元</font>";
        tb_pay_service_totle.setText(Html.fromHtml(money));
        if(TextUtils.isEmpty(ed_health_currency_num.getText().toString())){
            tv_pay_health_currrent.setText("0元");
        }
        //tb_pay_service.setTag(TOTTLE_ON);
        tb_pay_service.setChecked(false);
        ll_payforservice.setVisibility(View.GONE);
        tb_pay_service.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    money = "¥ "+ "<font color='#fc6f00'>"+MathUtils.getFloats(servicePrice)+"元</font>";
                    tb_pay_service_totle.setText(Html.fromHtml(money));
                    ed_health_currency_num.setEnabled(isChecked);
                    ed_health_currency_num.setClickable(isChecked);
                    ll_payforservice.setVisibility(View.GONE);
                } else {
                    String etRueslt = ed_health_currency_num.getText().toString();
                    if(!TextUtils.isEmpty(etRueslt)){
                        double etIntResult = Double.parseDouble(etRueslt);
                       /* double etIdResult = BigDecimalUtils.divide(String.valueOf(etIntResult),String.valueOf(100)).doubleValue();*/
                        //double etIdResult = etIntResult / 100;
                                money = "¥ "+ MathUtils.getFloats(servicePrice) +"-" +MathUtils.getFloats(etIntResult)+"=<font color='#fc6f00'>"+MathUtils.getFloats(currentAllMoney)+"元</font>";
                    }
                    ll_payforservice.setVisibility(View.VISIBLE);
                    tb_pay_service_totle.setText(Html.fromHtml(money));
                    ed_health_currency_num.setEnabled(isChecked);
                    ed_health_currency_num.setClickable(isChecked);
                }
            }
        });

    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName){
            case Act.Flag.FLAG_GET_USERHEALTH_MOENY_COUNT://获取健康币
                try {
                    String strObj = object.toString();
                    tv_pay_service_currency.setText("使用健康币 剩余可用 " + strObj + "元");

                    if(!TextUtils.isEmpty(strObj.toString())){

                        healthyCoinNum = Double.parseDouble(strObj.toString());
                        //int transCoin = Integer.parseInt(strObj.toString());
                        if(servicePrice >= healthyCoinNum && healthyCoinNum > 0){//计算   服务金额 > 健康币
                            currentCoinNum = healthyCoinNum;
                            currentAllMoney = servicePrice - healthyCoinNum;//减去健康币的剩下当前你的金额
                            //double etIdResult = BigDecimalUtils.divide(String.valueOf(currentCoinNum), String.valueOf(100)).doubleValue();
                            money = "¥ " +  MathUtils.getFloats(servicePrice) + "-" +  MathUtils.getFloats(currentCoinNum) + "=<font color='#fc6f00'>" +  MathUtils.getFloats(currentAllMoney) + "元</font>";
                            ed_health_currency_num.setHint("最多可用"+ MathUtils.getFloats(healthyCoinNum)+"");
                           // ll_payforservice.setVisibility(View.VISIBLE);
                        }else if(servicePrice   < healthyCoinNum && healthyCoinNum > 0){//计算   服务金额 < 健康币
                            tb_pay_service_totle.setText(Html.fromHtml(money));
                             currentCoinNum = servicePrice ;
                             currentAllMoney = servicePrice - healthyCoinNum;//减去健康币的剩下当前你的金额
                          //  double etIdResult = BigDecimalUtils.divide(String.valueOf(currentCoinNum), String.valueOf(100)).doubleValue();
                            money = "¥ " +  MathUtils.getFloats(servicePrice) + "-" + MathUtils.getFloats( healthyCoinNum) + "=<font color='#fc6f00'>" + MathUtils.getFloats( currentAllMoney) + "元</font>";
                            ed_health_currency_num.setHint("最多可用"+(int)(servicePrice)+"健康币");
                          //  ll_payforservice.setVisibility(View.VISIBLE);
                        }else{
                            ed_health_currency_num.setText("0");
                            ed_health_currency_num.setEnabled(true);
                          //  ll_payforservice.setVisibility(View.GONE);
                        }

                        ed_health_currency_num.setText(""+MathUtils.getFloats( currentCoinNum));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case Act.Flag.PAYMENTALIPAYAPI_FLAG://qingqiu之前请求前验证
                try{
                    String orderInfo = object.toString();
                    String signFlag = JsonUtils.getFiledData(orderInfo, "signFlag");
                    if(signFlag.equals("0")){//已经购买过啦
                        InquiryHintDialog dialog = new InquiryHintDialog(PayOrderServiceActivity.this)
                                .setMyCancelable(false)
                                .setMyOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        ActivityUtils.showActivity(PayOrderServiceActivity.this, MyNewDoctorActivity.class);
                                        finish();
                                    }
                                });
                        dialog.setWebContent(Apis.getTipUrl(Constants.H5_TIP_BUY_DOCTOR_SERVICE));
                        dialog.setCircleDialogAtter(0.8, 0.5);
                        dialog.setButtonSize(18);
                        if(!dialog.isShowing()){
                            dialog.show();
                        }
                    }else if(signFlag.equals("1")){//没有订购服务
                        String signString = JsonUtils.getFiledData(orderInfo, "signString");
                        payToOrderService(signString);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case Act.Flag.CREATESERVICEORDER_FLAG://创建送心意订单
                String data = (String) object;

                String mSignFlag = JsonUtils.getFiledData(data, "signFlag");
                if(TextUtils.isEmpty(mSignFlag)){
                }else if(mSignFlag.equals("0")){//是否验签 0 不验 1验签
                    GetToast.useString(PayOrderServiceActivity.this, "购买服务成功");
                    InquiryHintDialog dialog = new InquiryHintDialog(PayOrderServiceActivity.this)
                            .setMyCancelable(false)
                            .setMyOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ActivityUtils.showActivity(PayOrderServiceActivity.this, MyNewDoctorActivity.class);
                                    finish();
                                }
                            });
                    dialog.setWebContent(Apis.getTipUrl(Constants.H5_TIP_BUY_DOCTOR_SERVICE));
                    dialog.setCircleDialogAtter(0.8, 0.5);
                    dialog.setButtonSize(18);
                    if(!dialog.isShowing()){
                        dialog.show();
                    }
                    currentCoinNum = 0;
                }else if(mSignFlag.equals("1")){
                    String orderno = JsonUtils.getFiledData(data, "orderno");
                    provider.createServiceOrder(orderno);
                }
                break;
            case  Act.Flag.ALIPAYSIGN_FLAG://得到签名
                try{
                    String signFlag = object.toString();
                    if(!TextUtils.isEmpty(signFlag)){
                        payToOrderService(signFlag);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;

        }
    }
    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        switch (actionName){
        }
    }

    public void addEdittextListener(){
        ed_health_currency_num.setFilters(new InputFilter[] { lengthfilter });
        ed_health_currency_num.addTextChangedListener(new TextWatcher() {
            private int ss;

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable edit) {
                //edit  输入结束呈现在输入框中的信息
                if (!TextUtils.isEmpty(edit.toString())) {
                    String keywords = edit.toString();
                    if(keywords.startsWith("00")){
                         if(keywords.length() >= 2){
                             edit.delete(0,1);
                         }
                    }
                    double etIntputCoinNum = Double.parseDouble(keywords);

                    if (etIntputCoinNum == 0) {
                        money = "¥ " + "<font color='#fc6f00'>" +MathUtils.getFloats( servicePrice) + "元</font>";
                        tv_pay_health_currrent.setText(String.valueOf("0.00") + "元");
                        tb_pay_service_totle.setText(Html.fromHtml(money));
                        currentAllMoney = servicePrice;
                        currentCoinNum = etIntputCoinNum;
                        Selection.setSelection(ed_health_currency_num.getText(), ed_health_currency_num.getText().toString().length());
                    } else {
                        //double etInputCoinTotltMoney = etIntputCoinNum;
                        //double etIdResult = etIntResult / 100;
                       // double servicePrice1 = servicePrice;
                       // double etIntResult1 = etIntputCoinNum;
                        if (healthyCoinNum >= etIntputCoinNum) {//健康币总的数量 > 所输入健康币的数量

                            if (servicePrice > etIntputCoinNum) {
                                currentAllMoney = BigDecimalUtils.subtract(String.valueOf(servicePrice), String.valueOf(etIntputCoinNum)).doubleValue();//减去健康币的剩下当前你的金额
                                money = "¥ " + MathUtils.getFloats(servicePrice) + "-" + MathUtils.getFloats(etIntputCoinNum) + "=<font color='#fc6f00'>" + MathUtils.getFloats(currentAllMoney) + "元</font>";
                                currentCoinNum = etIntputCoinNum;
                            } else if (servicePrice == etIntputCoinNum) {
                                currentAllMoney = BigDecimalUtils.subtract(String.valueOf(servicePrice), String.valueOf(etIntputCoinNum)).doubleValue();//减去健康币的剩下当前你的金额
                                money = "¥ " + MathUtils.getFloats(servicePrice) + "-" + MathUtils.getFloats(etIntputCoinNum) + "=<font color='#fc6f00'>" + MathUtils.getFloats(0) + "元</font>";
                                Selection.setSelection(ed_health_currency_num.getText(), keywords.length());
                                currentCoinNum = etIntputCoinNum;
                            } else if (servicePrice < etIntputCoinNum) {
                               // Selection.setSelection(ed_health_currency_num.getText(), ed_health_currency_num.getText().toString().length());
                                if(ed_health_currency_num.getText().length() > 0){
                                    int index = ed_health_currency_num.getSelectionStart();
                                    if(index == 1){
                                        Editable editable = ed_health_currency_num.getText();
                                        editable.delete(index-1, index);
                                        GetToast.useString(PayOrderServiceActivity.this, "不需这么多健康币");
                                        return;
                                    }
                                }
                                String newStr = edit.toString().substring(0, edit.toString().length() - 1);
                                if(TextUtils.isEmpty(newStr)){
                                    newStr = "0";
                                }
                                // healthycoin = newStr;
                                ed_health_currency_num.setText(newStr);
                                GetToast.useString(PayOrderServiceActivity.this, "不需这么多健康币");
                                return;
                            }
                        } else {//健康币总的数量 < 所输入健康币的数量
                            if(ed_health_currency_num.getText().length() > 0){
                                int index = ed_health_currency_num.getSelectionStart();
                                if(index == 1){
                                    Editable editable = ed_health_currency_num.getText();
                                    editable.delete(index-1, index);
                                    return;
                                }
                            }
                            //截取新字符串
                            String newStr = edit.toString().substring(0, edit.toString().length() - 1);
                            if(TextUtils.isEmpty(newStr)){
                                newStr = "0";
                            }
                            ed_health_currency_num.setText(newStr);
                            etIntputCoinNum = Double.parseDouble(ed_health_currency_num.getText().toString());
                            //新字符串的长度
                            int newLen = ed_health_currency_num.getText().toString().length();
                            ed_health_currency_num.setSelection(newLen);
                            GetToast.useString(PayOrderServiceActivity.this, "您没有这么多健康币");
                        }
                        try {
                            //设置新光标所在的位置
                            Selection.setSelection(ed_health_currency_num.getText(), ed_health_currency_num.getText().toString().length());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (tb_pay_service.isChecked()) {
                            tb_pay_service_totle.setText(Html.fromHtml(money));
                        } else {
                            String notOpenServiceSetting = "¥ " + "<font color='#fc6f00'>" + MathUtils.getFloats(servicePrice) + "元</font>";
                            tb_pay_service_totle.setText(Html.fromHtml(notOpenServiceSetting));
                        }
                        tv_pay_health_currrent.setText(MathUtils.getFloats( etIntputCoinNum) + "元");
                    }
                   /* healthycoin = String.valueOf(ed_health_currency_num.getText().toString().trim());*/
                } else {
                    currentAllMoney = servicePrice;
                    money = "¥ " + "<font color='#fc6f00'>" + MathUtils.getFloats(servicePrice) + "元</font>";
                    currentCoinNum = 0;
                    tv_pay_health_currrent.setText(String.valueOf("0.00") + "元");
                    tb_pay_service_totle.setText(Html.fromHtml(money));
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.btn_order_service_pay:
                payAliyunment();
                break;
        }
    }
    private void payToOrderService(final String signInfo) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                PayTask payTask = new PayTask(PayOrderServiceActivity.this);
                // String result = payTask.pay(signInfo, true);
                Map<String, String> result = payTask.payV2(signInfo, true);
                Message message = mHandler.obtainMessage();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);

            }
        }.start();
    }

    /**
     * *  设置小数位数控制
    */
    InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };
    /** 输入框小数的位数*/
    private static final int DECIMAL_DIGITS = 2;
}
